<?php
namespace app\admin\controller;
use app\model\Admin;
use app\model\System;
use app\util\ReturnCode;
use app\util\Tools;

class Sys extends Base
{

    protected $admin;
    protected $system;

    public function __construct(Admin $admin, System $system)
    {
        parent::__construct();
        $this->admin = $admin;
        $this->system = $system;
    }

    /**
     * 系统基本设置
     * @return string
     */
    public function site(){
        $info = cache('siteSet');
        if(!$info){
            try {
                $info = System::find(['id' => 1]);
                $info = $this->system->where(['id'=>1])->find();
            } catch (\Exception $e) {
                $info = [];
            }
        }
        return $this->buildSuccess($info);
    }

    /**
     * 保存基本设置
     * @return false|string
     */
    public function siteSave(){
        $data = $this->request->post();
        $this->system->allowField(true)->save($data,['id'=>1]);
        cache('siteSet', $data);
        return $this->buildSuccess([]);
    }

    /**
     * 管理员列表
     * @return false|string
     */
    public function adminList(){
        $page = $this->request->post('page',1);
        $size = $this->request->post('size',10);
        $data = $this->admin->getList(1,$page, $size);
        return $this->buildSuccess($data);
    }

    /**
     * 编辑管理员
     * @return string
     */
    public function adminSave(){
        $data = $this->request->post();
        $id = $this->request->post('id');
        if($id){
            if(isset($data['password']) && !empty($data['password']))
                $data['password'] = Tools::userMd5($data['password']);
            $this->admin->allowField(true)->save($data,['id'=>$id]);
            return $this->buildSuccess([]);
        }else{
            if($this->admin->where(['username' => $data['username']])->count())
                return $this->buildFailed(ReturnCode::REPEAT_OF_USERNAME, '用户名重复');
            $data['password'] = Tools::userMd5($data['password']);
            $data['create_time'] = time();
            $res = $this->admin->insert($data);
            if($res)
                return $this->buildSuccess([]);
            else
                return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '参数错误');
        }
    }

    /**
     * 删除管理员
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function adminDel(){
        $id = $this->request->post('id',0);
        if(!$id)
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS,'参数错误');
        $this->admin->where(['id'=>$id])->delete();
        return $this->buildSuccess([]);
    }


}
